﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using BLL;
using Model;
using Aspose.Words;
using Aspose.Words.Saving;
using Aspose.Words.Drawing;

namespace WebApp.Controllers
{
    public class HomeController : Controller
    {
        public HomeController():base()
        {
        }
        ContractService contractService = new ContractService();
        public ActionResult Index()
        {
            //List<hetongjbxx> list = contractService.GetHetongjbxxes();
            //ViewData["hetongjbxx"] = list;
            return GenerateContract(0);
            //return View();
        }
        /// <summary>
        /// 生成合同
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult GenerateContract(int id)
        {
            string filePath = Server.MapPath("~/生成的word/");
            DeleteDir(filePath);
            //DataSet dsData = contractService.GenerateContract(id);
            string fileName = GetWordContent(null);
            return File(fileName, "application/msword");
        }
        /// <summary>
        /// 生成合同内容
        /// </summary>
        /// <returns></returns>
        private string GetWordContent(DataSet ds)
        {
            #region 最新代码
            string tempPath = Server.MapPath("~/documents/合同模板.docx");
            Document doc = new Document(tempPath);
            ////获取doc里面的 域名字
            //string[] all = doc.MailMerge.GetFieldNames();
            //doc.MailMerge.Execute(ds.Tables[0]);
            //NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true); //拿到所有表格
            //Aspose.Words.Tables.Table table = allTables[1] as Aspose.Words.Tables.Table; //拿到第1个表格
            //int i=0;
            ////在这里循环产品列表对象
            //foreach (DataRow item in ds.Tables[1].Rows)
            //{
            //    var row = CreateRow(8, (new string[] { 
            //        item["chanpinmc"].ToString(), item["xinghao"].ToString(), item["pinpai"].ToString(), item["chandi"].ToString(),
            //        item["danjia"].ToString(), item["danwei"].ToString(), item["shuliang"].ToString(), 
            //        item["xiaoji"].ToString()
            //    }), doc); //创建一行
            //    i++;
            //    table.Rows.Insert(i, row); //将此行插入第一行的上方
            //}
            Bookmark mark = doc.Range.Bookmarks["shebeiqingdan"];  //这里我是测试了一下 用书签来 替换
            string shebeipath= Server.MapPath("~/documents/配置清单.doc");
            Document doc1 = new Document(shebeipath);
            //指定节点插入另一个文档的内容改为这个
            InsertDocument(mark.BookmarkStart.ParentNode, doc1);
            //mark.Text = doc1.GetText();

            string jishuzhibiaoPath = Server.MapPath("~/documents/技术指标.doc");
            mark = doc.Range.Bookmarks["jishuqingdan"];  //这里我是测试了一下 用书签来 替换
            doc1 = new Document(jishuzhibiaoPath);
            //mark.Text = doc1.GetText();
            //指定节点插入另一个文档的内容改为这个
            InsertDocument(mark.BookmarkStart.ParentNode, doc1);
            #region 指定位置插入图片
            DocumentBuilder builder = new DocumentBuilder(doc);
            Shape shape = new Shape(doc, ShapeType.Image);
            shape.ImageData.SetImage(Server.MapPath("~/Images/1.jpg"));
            shape.Width = 70;//设置宽和高
            shape.Height = 70;
            shape.WrapType = WrapType.None;
            shape.BehindText = true;

            //shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
            //shape.HorizontalAlignment = HorizontalAlignment.Center;
            //shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;
            //shape.VerticalAlignment = VerticalAlignment.Center;
            //shape.HorizontalAlignment = HorizontalAlignment.Center; 
            builder.MoveToBookmark("LogoImage");
            builder.InsertNode(shape);
            #endregion

            string fileName = Guid.NewGuid().ToString();
            fileName = Server.MapPath("~/生成的word/" + fileName + ".docx");
            //fileName = "/生成的word/" + fileName + ".docx";
            doc.Save(fileName);
            //MemoryStream ms = new MemoryStream();
            //SaveOutputParameters saveOutputParameters = doc.Save(ms, SaveFormat.WordML);
            return fileName;
            #endregion
        }

        Aspose.Words.Tables.Row CreateRow(int columnCount, string[] columnValues, Document doc)
        {
            Aspose.Words.Tables.Row r2 = new Aspose.Words.Tables.Row(doc);
            for (int i = 0; i < columnCount; i++)
            {
                if (columnValues.Length > i)
                {
                    var cell = CreateCell(columnValues[i], doc);
                    r2.Cells.Add(cell);
                }
                else
                {
                    var cell = CreateCell("", doc);
                    r2.Cells.Add(cell);
                }

            }
            return r2;
        }

        Aspose.Words.Tables.Cell CreateCell(string value, Document doc)
        {
            Aspose.Words.Tables.Cell c1 = new Aspose.Words.Tables.Cell(doc);
            Paragraph p = new Paragraph(doc);
            p.AppendChild(new Run(doc, value));
            c1.AppendChild(p);
            return c1;
        }

        #region 直接删除指定目录下的所有文件及文件夹(保留目录)
        public void DeleteDir(string file)
        {
            try
            {
                //去除文件夹和子文件的只读属性
                //去除文件夹的只读属性
                System.IO.DirectoryInfo fileInfo = new DirectoryInfo(file);
                fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;

                //去除文件的只读属性
                System.IO.File.SetAttributes(file, System.IO.FileAttributes.Normal);

                //判断文件夹是否还存在
                if (Directory.Exists(file))
                {
                    foreach (string f in Directory.GetFileSystemEntries(file))
                    {
                        if (System.IO.File.Exists(f))
                        {
                            //如果有子文件删除文件
                            System.IO.File.Delete(f);
                            Console.WriteLine(f);
                        }
                        else
                        {
                            //循环递归删除子文件夹
                            DeleteDir(f);
                        }
                    }

                    //删除空文件夹
                    Directory.Delete(file);
                    Console.WriteLine(file);
                }

            }
            catch (Exception ex) // 异常处理
            {
                Console.WriteLine(ex.Message.ToString());// 异常信息
            }
        }
        #endregion
        #region 新添加的方法
        /// <summary>
        /// 在指定节点之后插入外部文档的内容。
        /// 插入文档的分节符和节格式将被忽略。
        /// </summary>
        /// <param name="insertAfterNode">Node in the destination document after which the content
        /// Should be inserted. This node should be a block level node (paragraph or table).</param>
        /// <param name="srcDoc">The document to insert.</param>
        static void InsertDocument(Node insertAfterNode, Document srcDoc)
        {
            // Make sure that the node is either a paragraph or table.
            if ((!insertAfterNode.NodeType.Equals(NodeType.Paragraph)) &
              (!insertAfterNode.NodeType.Equals(NodeType.Table)))
                throw new ArgumentException("The destination node should be either a paragraph or table.");

            // We will be inserting into the parent of the destination paragraph.
            CompositeNode dstStory = insertAfterNode.ParentNode;

            // This object will be translating styles and lists during the import.
            NodeImporter importer = new NodeImporter(srcDoc, insertAfterNode.Document, ImportFormatMode.KeepSourceFormatting);

            // Loop through all sections in the source document.
            foreach (Section srcSection in srcDoc.Sections)
            {
                // Loop through all block level nodes (paragraphs and tables) in the body of the section.
                foreach (Node srcNode in srcSection.Body)
                {
                    // Let's skip the node if it is a last empty paragraph in a section.
                    if (srcNode.NodeType.Equals(NodeType.Paragraph))
                    {
                        Paragraph para = (Paragraph)srcNode;
                        if (para.IsEndOfSection && !para.HasChildNodes)
                            continue;
                    }

                    // This creates a clone of the node, suitable for insertion into the destination document.
                    Node newNode = importer.ImportNode(srcNode, true);

                    // Insert new node after the reference node.
                    dstStory.InsertAfter(newNode, insertAfterNode);
                    insertAfterNode = newNode;
                }
            }
        } 
        #endregion
    }
}